package com.kefu.call.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.call.model.CdrCustomer;
import com.kefu.call.service.CdrCustomerService;
import com.kefu.common.mybatis.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kefu.common.controller.AbstractBaseController;
import com.kefu.common.result.Result;
import com.kefu.common.result.ResultGenerator;
import com.kefu.call.model.CdrRghistory;
import com.kefu.call.service.CdrRghistoryService;
import com.kefu.call.vo.CdrRghistorySearchVo;
import com.kefu.call.vo.CdrRghistoryInsertVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "计费_充值表")
@RestController
@RequestMapping("call/cdr_rghistory")
public class CdrRghistoryController extends AbstractBaseController {

    @Autowired
    private CdrRghistoryService cdrRghistoryService;
    @Autowired
    CdrCustomerService cdrCustomerService;

    @PostMapping("/add")
    @ApiOperation(value = "新增计费_充值表", notes = "新增计费_充值表")
    public Result<String> add(@Validated @RequestBody CdrRghistoryInsertVo cdrRghistoryVo) {
        logger.info("新增计费_充值表:{}", cdrRghistoryVo);

        CdrCustomer cdrCustomer = cdrCustomerService.getOne(Wrappers.lambdaQuery(CdrCustomer.class).eq(CdrCustomer::getCompany, cdrRghistoryVo.getCompany()));
        String newBalance = String.valueOf(Double.parseDouble(cdrCustomer.getBalance()) + Double.parseDouble(cdrRghistoryVo.getRgmoney()));
        CdrRghistory info = cdrRghistoryVo.convert();
        info.setBeforemoney(cdrCustomer.getBalance());
        info.setAftermoney(newBalance);
        logger.info("呼叫余额增加:{},{},{}", cdrCustomer, cdrRghistoryVo, newBalance);
        cdrCustomerService.update(Wrappers.lambdaUpdate(CdrCustomer.class).set(CdrCustomer::getBalance, newBalance).eq(CdrCustomer::getOid, cdrCustomer.getOid()));
        cdrRghistoryService.save(info);
        return ResultGenerator.genSuccessResult();
    }


    @PostMapping("/list")
    @ApiOperation(value = "查询计费_充值表", notes = "查询计费_充值表")
    public Result<Page<CdrRghistory>> list(@Validated @RequestBody CdrRghistorySearchVo search) {

        search.setOrderField("oid");
        search.setOrder(Order.DESC);
        Page<CdrRghistory> page = cdrRghistoryService.searchLambdaPage(search);
        return ResultGenerator.genSuccessResult(page);
    }
}
